package com.industrial.operation.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.nacos.api.utils.StringUtils;
import com.industrial.common.core.utils.DateUtils;
import com.industrial.common.core.utils.uuid.IdUtils;
import com.industrial.common.core.web.domain.AjaxResult;
import com.industrial.common.security.utils.SecurityUtils;
import com.industrial.operation.domain.SysDataReportingFile;
import com.industrial.operation.mapper.SysDataReportingFileMapper;
import com.industrial.operation.service.ISysDataReportingFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class SysDataReportingFileServiceImpl implements ISysDataReportingFileService {

    @Autowired
    private SysDataReportingFileMapper sysDataReportingFileMapper;

    @Value("${file.domain}")
    private String fileDomain;

    @Override
    public AjaxResult saveFileInfo(SysDataReportingFile sysDataReportingFile) {

        String pkId = sysDataReportingFile.getPkId();
        List<SysDataReportingFile> result = sysDataReportingFileMapper.selectSysDataReportingFileListById(pkId);

        if(result != null && !result.isEmpty()){
            return AjaxResult.warn("您已上传了一份材料。");
        }
        sysDataReportingFile.setBaseId(IdUtils.simpleUUID());
        sysDataReportingFile.setBaseCreateTime(DateUtils.getNowDate());
        sysDataReportingFile.setBaseCreateBy(SecurityUtils.getUserId());
        //替换文件路径
        String filePath = sysDataReportingFile.getFilePath();
        String path = StrUtil.removePrefix(filePath, fileDomain);
        sysDataReportingFile.setFilePath("/file" + path);
        sysDataReportingFileMapper.insertSysDataReportingFileInfo(sysDataReportingFile);
        return AjaxResult.success("附件保存成功");
    }

    @Override
    public AjaxResult getFileInfoByPkId(String pkId) {
        SysDataReportingFile result = sysDataReportingFileMapper.getFileInfoByPkId(pkId);
        if(Objects.isNull(result)){
            return AjaxResult.success(new ArrayList<SysDataReportingFile>());
        }
        return AjaxResult.success(result);
    }

    @Override
    public AjaxResult deleteFileInfoById(SysDataReportingFile sysDataReportingFile) {
        if(StringUtils.isBlank(sysDataReportingFile.getBaseId())){
            return AjaxResult.warn("文件Id不能为空");
        }
        sysDataReportingFileMapper.deleteFileInfoById(sysDataReportingFile);
        return AjaxResult.success("删除成功；");
    }
}
